from django import forms
from apps.forms import FormMixin
from django.core.cache import cache
from .models import User


class LoginForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11)
    password = forms.CharField(max_length=20,min_length=6,error_messages={"max_length":"密码最多不能超过20个字符！","min_length":"密码最少不能少于6个字符！"})
    remember = forms.IntegerField(required=False)


class RegisterForm(forms.Form, FormMixin):
    telephone = forms.CharField(max_length=11)
    username = forms.CharField(max_length=20)
    password1 = forms.CharField(max_length=20, min_length=6, error_messages={"max_length":"密码最多不能超过20个字符！","min_length":"密码最少不能少于6个字符！"})
    password2 = forms.CharField(max_length=20, min_length=6, error_messages={"max_length": "密码最多不能超过20个字符！", "min_length": "密码最少不能少于6个字符！"})
    img_captcha = forms.CharField(max_length=4, min_length=4)
    sms_captcha = forms.CharField(max_length=4, min_length=4)

    def clean(self):
        clean_date = super(RegisterForm, self).clean()
        password1 = clean_date.get('password1')
        password2 = clean_date.get('password2')
        img_captcha = clean_date.get('img_captcha')
        telephone = clean_date.get('telephone')
        sms_captcha = clean_date.get('sms_captcha')
        # cached_img_captcha = cache.get(img_captcha.lower())
        if password1 != password2:
            raise forms.ValidationError("两次密码不一致！")
        # if not cached_img_captcha or cached_img_captcha.lower() == img_captcha.lower():
        if img_captcha != "1234":
            raise forms.ValidationError("验证码不正确！")
        if sms_captcha != "1234":
            raise forms.ValidationError("短信验证码不正确！")

        user = User.objects.filter(telephone=telephone)
        if user:
            raise forms.ValidationError("用户已存在！")